﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using IdentityServer4.Extensions;
using Microsoft.Extensions.Configuration;

namespace Authorize.Core.Configuration
{
    public static class AppConfigurations
    {
        private static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache;

        static AppConfigurations()
        {
            ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
        }

        public static IConfigurationRoot Get(string path, string enviromentName = null)
        {
            var cacheKey = path + "#" + enviromentName + "#";
            return ConfigurationCache.GetOrAdd(cacheKey,
                _ => BuildConfiguration(path, enviromentName));
        }

        private static IConfigurationRoot BuildConfiguration(string path, string enviromentName = null)
        {
            var builder = new ConfigurationBuilder().SetBasePath(path).AddJsonFile("appsettings.json", true, true);

            if (!enviromentName.IsNullOrEmpty())
            {
                builder = builder.AddJsonFile($"appsettings.{enviromentName}.json", true);
            }

            builder = builder.AddEnvironmentVariables();

            return builder.Build();
        }
    }
}
